/**
 * 图网络构建 store
 * @author JinHui Hou
 */
import {
  Module,
  Mutation,
  VuexModule,
  getModule,
  Action,
} from 'vuex-module-decorators'
import store from '@/store'
import { graphQueryAction, graphDeleteAction } from '@/api/visualization'
import { message } from 'ant-design-vue'
import { getUserInfo } from '@/api/user'
import { taskQueryById } from '@/api/task'
// import { apiUpdateHistory } from '@/api/data-clean'

interface SelectedCurrentEdge {
  model: any
  source: any
  target: any
}

export interface IKeyValueStore {
  [key: string]: any
}

@Module({ dynamic: true, namespaced: true, name: 'GraphBuild', store })
class GraphBuild extends VuexModule {
  private _selectedEdge: SelectedCurrentEdge | null = null // 构建图当前选择的边
  private _currentCategoryData: any = {} // 当前选中模型节点的模型数据
  private _edgeSetDrawerStatus: boolean = false // 网络构建边配置抽屉状态
  private _sourceNode: any = null // _selectedEdge 构建图当前边 的起始节点
  private _targetNode: any = null // _selectedEdge 构建图当前边 的结束节点
  private _firstSaveGraphAnalysis: boolean = false // 记录首次 构建右边图分析 用与保存 // g6 弃用
  private _isBatchSave: boolean = true // 是否已经保存网络分析图
  private _tableData: any = []
  private _currentNodeHistory: any = [] // 网络构建 节点操作的历史记录
  private _currentSelectedHistory: any = [] // 当前选中的历史纪录条目
  private _isBuildingGraph: number = 1 // 左侧图构建正在构建 1-初始状态 2-构建中 3-构建成功 4-构建失败
  // graph 构建成功后保存状态, 1 等待保存, 2 保存成功，3 保存失败
  private _graphSaveStatus: any = { type: 2, lastSaveTime: 0 } // 第一次构建修改， 保存修改接口回调修改

  private _graphBuildTaskInfo: any = {} // 当前图构建的信息（更加图构建节点id查询， 主要使用其创建者）
  private _userInfo: any = {} // 用户信息

  /** ====== get ====== */
  // 构建图当前选择的边
  public get selectedEdge() {
    return this._selectedEdge
  }
  // 构建图当前选择的节点
  public get currentCategoryData() {
    return this._currentCategoryData
  }
  // 网络构建边配置抽屉状态
  public get edgeSetDrawerStatus() {
    return this._edgeSetDrawerStatus
  }
  // 获取当前选边的起始节点
  public get selectedEdgeSourceNode() {
    return this._sourceNode
  }
  // 获取当前选边的结束节点
  public get selectedEdgeTargetNode() {
    return this._targetNode
  }
  // 获取是否首次生成构建,
  public get getFirstSaveGraphAnalysis() {
    return this._firstSaveGraphAnalysis
  }
  // 获取保存状态
  public get isBatchSave() {
    return this._isBatchSave
  }

  public get getTableData() {
    return this._tableData
  }

  // 当前节点的历史记录
  public get currentNodeHistory() {
    return this._currentNodeHistory
  }
  public get isBuildingGraph() {
    return this._isBuildingGraph
  }

  // 当前选中的历史记录条目
  public get currentSelectedHistory() {
    return this._currentSelectedHistory
  }

  public get graphSaveStatus() {
    return this._graphSaveStatus
  }

  public get graphBuildTaskInfo() {
    return this._graphBuildTaskInfo
  }

  public get graphBuildTaskName() {
    return this._graphBuildTaskInfo?.name
  }

  // 根据节点所有者 和 用户 id 判断该图构建所属
  public get isGraphSelfCreate() {
    return Object.keys(this._userInfo).length > 0 &&
      Object.keys(this._graphBuildTaskInfo).length > 0
      ? this._userInfo.id === this._graphBuildTaskInfo.userId
      : false
  }

  /** ====== Mutation ====== */
  // 更新构建图当前选择的边
  @Mutation
  public setSelectedEdge(edgeInfo: any) {
    this._selectedEdge = edgeInfo
  }
  // 更新当前选中的节点
  @Mutation
  public setCurrentCategoryData(data: any) {
    this._currentCategoryData = data
  }
  // 更新网络构建边配置抽屉状态
  @Mutation
  public setEdgeSetDrawerStatus(status: boolean) {
    this._edgeSetDrawerStatus = status
  }
  // 更新当前选边的起始节点
  @Mutation
  public setEdgeSourceNode(node: any) {
    this._sourceNode = node
  }
  // 更新当前选边的结束节点
  @Mutation
  public setEdgeTargetNode(node: any) {
    this._targetNode = node
  }
  // 首次保存图分析结果
  @Mutation
  public setFirstSaveGraphAnalysis(status: boolean) {
    this._firstSaveGraphAnalysis = status
  }
  // 设置已包存的状态
  @Mutation
  public setIsBatchSave(status: boolean) {
    this._isBatchSave = status
  }

  @Mutation
  public setTableData(data: any) {
    this._tableData = data
  }

  // 更新当前节点的历史记录
  @Mutation
  public setCurrentNodeHistory(data: any) {
    this._currentNodeHistory = data
    this._currentSelectedHistory =
      data.currentHistory || data.historyList.slice(-1)[0]
  }

  // 重新设置当前选中的历史纪录条目
  @Mutation
  public setCurrentSelectedHistory(history: IKeyValueStore | null) {
    this._currentSelectedHistory = history
  }

  /**
   * 1-初始状态 2-构建中 3-构建成功 4-构建失败
   * @param buildStatus
   */
  @Mutation
  public setIsBuildingGraph(buildStatus: number) {
    this._isBuildingGraph = buildStatus
  }

  @Mutation
  public setGraphSaveStatus(status: { type: number; lastSaveTime: any }) {
    this._graphSaveStatus = status
  }

  @Mutation
  public currentGraphBuildInfo(info: any) {
    this._graphBuildTaskInfo = info
  }

  @Mutation
  public setCurrentUserInfo(userInfo: any) {
    this._userInfo = userInfo
  }

  /** ====== Action ====== */
  @Action({ commit: 'setCurrentNodeHistory' })
  public async getHistoryList(graphId?: any) {
    const response = await graphQueryAction({
      data: {
        graphId,
        categoryId: this.currentCategoryData.id,
      },
    })
    const data = response.data.result
    const errorIndex = data.findIndex(
      (item: any) => item.data.status !== 'SUCCESS'
    )
    return {
      historyList: data,
      currentHistory: errorIndex > -1 ? data[errorIndex - 1] : null,
    }
  }

  /**
   * 删除操作历史记录
   * @param params id: xxx 要删除的历史记录id
   */
  @Action
  public async delHistory(parameters: any) {
    const response = await graphDeleteAction({
      data: {
        categoryId: this._currentCategoryData.id,
        ...parameters,
      },
    })
    return response.data
  }

  // 查询节点信息
  @Action({ commit: 'currentGraphBuildInfo' })
  public async queryTaskInfoById(id: any) {
    const result = await taskQueryById({
      data: { id },
    })
    let userRole: any = {}
    if (result.data.code === 100) {
      const { userId, pipelineId, projectId, name } = result.data.result
      userRole = { userId, pipelineId, projectId, name }
    } else {
      message.error(result.data.message)
    }
    return userRole
  }

  // 获取用户信息
  @Action({ commit: 'setCurrentUserInfo' })
  public async queryUserInfo() {
    const result: any = await getUserInfo()
    if (result.data.code === 100) {
      return result.data.result.user
    }
    return {}
  }
}

export default getModule(GraphBuild)
